<script lang="ts" setup>
import type { FormRules } from 'element-plus'
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { putPassword } from '@/api/userinfo.js'
import { useRouter } from 'vue-router'
const router = useRouter()

const formLabelWidth = '140px'
//显示dialog

const openDiaLog = () => {
    changePassword.value = true
}
//改密码组件显示
const changePassword = ref(false)
//修改新密码 id  oldPassword  newPassword
const resetPassword = async () => {
    const id = localStorage.getItem('id')
    if (changeUserPass.oldPassword && changeUserPass.newPassword) {
        const res = await putPassword(id, changeUserPass.oldPassword, changeUserPass.newPassword)
        console.log(res);
        if (res.status == 0) {
            ElMessage.success('修改密码成功')
            //关闭修改页面
            changePassword.value = false
            //跳转登录页，重新登录
            router.push({ path: '/login' })
        } else {
            ElMessage.error('修改密码失败')
        }

    } else {
        ElMessage.error('修改密码失败,请检查输入')
    }


}
//表单数据
interface changeUserPass {
    oldPassword: string
    newPassword: string
}
const changeUserPass: changeUserPass = reactive({
    oldPassword: '',
    newPassword: ''

})

//导出方法
defineExpose({
    openDiaLog
})
const rules = reactive<FormRules<changeUserPass>>({
    oldPassword: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
    newPassword: [
        {
            required: true,
            message: '请输入密码',
            trigger: 'blur',
        },
    ],
})

</script>

<template>
    <!-- 修改密码 -->
    <el-dialog v-model="changePassword" title="修改密码" width="30%" draggable>
        <el-form :model="changeUserPass" label-position="top" :rules="rules">
            <el-form-item prop="password" label="输入旧密码" :label-width="formLabelWidth">
                <el-input v-model="changeUserPass.oldPassword" placeholder="输入旧密码" />
            </el-form-item>
            <el-form-item prop="newPassword" label="输入新密码" :label-width="formLabelWidth">
                <el-input v-model="changeUserPass.newPassword" show-password  placeholder="输入新密码"/>
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="changePassword = false">关闭</el-button>
                <el-button type="primary" @click="resetPassword">
                    确认
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>


<style scoped lang="scss">

</style>